package com.ilvyou.api.controller.finance;

import com.ilvyou.api.common.Cache;
import com.ilvyou.api.common.Constant;
import com.ilvyou.api.controller.BaseController;
import com.ilvyou.api.bean.result.Result;
import com.ilvyou.api.service.FinanceService;
import com.ilvyou.api.service.PersonalService;
import com.ilvyou.api.service.UserService;
import com.ilvyou.api.util.RemoteUtil;
import com.ilvyou.core.dao.Criteria;
import com.ilvyou.core.dao.Query;
import com.ilvyou.core.util.StringUtil;
import com.ilvyou.data.lhf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by GuanYuCai on 16/9/17.
 */
@Controller
public class TransferController extends BaseController {

    @Autowired
    private FinanceService financeService;
    @Autowired
    private UserService userService;
    @Autowired
    private PersonalService personalService;

    @RequestMapping("/transfer/accountInfo")
    @ResponseBody
    public Result accountInfo(@RequestParam String account, @RequestParam String token) throws Exception{
        ScrAlipayEntity entity = userService.getScrAlipayEntityByAccount(account);
        if(entity == null || entity.getEnableflag() != 1){ //该账户不存在
            return fail("该账号不存在");
        }

        return success(entity, "actid,actname,realname,nickname,mobile,bppcompanyname,faceurl");
    }

    @RequestMapping(value="/transfer/submit", method=RequestMethod.POST)
    @ResponseBody
    public Result transfer(@RequestParam String account, @RequestParam String token, @RequestParam double money,
                              @RequestParam String paypassword, String note) throws Exception{
        if (money <= 0){
            return fail("金额不能小于零");
        }

        note = StringUtil.isEmpty(note) ? "" : note;

        Cache.User user = Cache.get(token);
        long actId = user.actId;

        //获得转入转出的账户
        ScrAlipayEntity alipayOut = userService.getByPK(ScrAlipayEntity.class, actId);
        ScrAlipayEntity alipayIn = userService.getScrAlipayEntityByAccount(account);
        SrcAuthbaseEntity srcAuthBase = personalService.getAuthbaseByActid(actId);
        if (StringUtil.isEmpty(alipayOut.getBpploginname()) || srcAuthBase == null){
            return fail("请先前往电脑端补全信息，再进行操作。");
        }
        if(alipayIn == null || alipayIn.getEnableflag() != 1){ //该账户不存在
            return fail("该账号不存在");
        }if(actId == alipayIn.getActid()){
            return fail("不能向用户自身转账");
        }else if(alipayIn.getBppagentcategory() == Constant.BppAccountType.BPP_AGENT_CATEGORY_OTHER){
            return fail("该账户不支持转账操作");
        }else if((alipayOut.getBppagentcategory() == Constant.BppAccountType.BPP_AGENT_CATEGORY_SPECIAL)
                && (alipayIn.getBppagentcategory() == Constant.BppAccountType.BPP_AGENT_CATEGORY_TRAVEL)){
            //专线商不支持向旅行社转账的功能
            return fail("暂不支持您向组团社转账");
        }

        //获取转入转出的账期
        AlipayPeriodEntity periodOut = financeService.getAlipayPeriod(actId);
        AlipayPeriodEntity periodIn = financeService.getAlipayPeriod(alipayIn.getActid());
        if(periodOut == null || periodIn == null){
            return fail("该用户不能进行金额操作");
        }

        AlipayAccountEntity accountOut = userService.getByPK(AlipayAccountEntity.class, actId);
        AlipayAccountEntity accountIn = userService.getByPK(AlipayAccountEntity.class, alipayIn.getActid());

        paypassword = StringUtil.base64Decode(paypassword);
        paypassword = RemoteUtil.getMd5Pwd(paypassword, alipayOut.getSalt());
        if (!paypassword.equals(accountOut.getPaypassword())){
            return fail("交易密码不正确");
        }

        if(money > accountOut.getRightamount()){ //转账的金额超过账户的余额
            return fail("金额不足，可先充值");
        }

        long id = financeService.addTransfer(alipayOut, alipayIn, accountOut, accountIn, periodOut, periodIn, money, note, user.source);
        return success("transferid", id);
    }

    @RequestMapping("/transfer/accountList")
    @ResponseBody
    public Result transferAccounts(@RequestParam String token, int pageno, int pagesize) throws Exception{
        Query query = new Query(AlipayTransferEntity.class, "a.tactid as actid")
                .leftJoin(ScrAlipayEntity.class, "b.bppcompanyname as companyname,b.mobile,b.faceurl",
                        new Criteria("a.tactid=b.actid"))
                .where(new Criteria("factid=?", getUserId(token)))
                .page(pageno, pagesize);
        return success(financeService.getMapList(query));
    }

    @RequestMapping(value="/transfer/sendMessage", method=RequestMethod.POST)
    @ResponseBody
    public Result sendMessage(@RequestParam String token, @RequestParam long transferid) throws Exception{
        AlipayTransferEntity transfer = financeService.getByPK(AlipayTransferEntity.class, transferid);
        if (transfer == null){
            return fail("该转账不存在");
        }

        financeService.sendTransferMessage(transfer);
        return success("");
    }
}
